﻿using DevComponents.DotNetBar.SuperGrid;
using SCBX;
using SDATA;
using SDLL;
using SGUI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SABI
{
    public partial class frm0217 : Form
    {

        string sql, _VoucherID, _BatchID = "";

        IGB igb = new IGB(FRM.ConnectString);
        IGB igb2 = new IGB(FRM.ConnectString);
        IGB igb3 = new IGB(FRM.ConnectString);

        bool _isNew = true;
        bool _isDuplicate = false;
        bool _isSlitA = true; // true = Quantity; false = Amount;
        
        double _TotalPrice = 0;
        double _TotalQuantity = 0;
        double _TotalImTax = 0;        

        public frm0217()
        {
            InitializeComponent();
        }

        public frm0217(bool isNew = true, bool isView = false, string VoucherID = "", bool isDuplicate=false)
        {
            InitializeComponent();
            _isNew = isNew;
            _isDuplicate = isDuplicate;
            btnSave.Visible = !isView;

            txtVoucherNo.Enabled = isNew;
            TDBCboVoucherTypeID.Enabled = isNew;
            //txtVoucherNo2.Enabled = isNew;
            //TDBCboVoucherTypeID2.Enabled = isNew;
            //TDBCboEmployeeID2.Enabled = isNew;
            //txtVoucherNo3.Enabled = isNew;
            //TDBCboVoucherTypeID3.Enabled = isNew;

            btnNext.Visible = isNew;
            GridDB1.PrimaryGrid.ReadOnly = isView;
            _VoucherID = VoucherID;
        }

        private void frm0217_Load(object sender, EventArgs e)
        {

        }

        private void frm0217_Shown(object sender, EventArgs e)
        {
            loadDATA_Combo();
            loadDATA_Combo2();
            loadDATA_Combo3();

            if (_isNew||_isDuplicate)
            {
                TDBCboVoucherTypeID.SelectedValue = "MH";
                TDBCboCurrencyID.SelectedValue = "VND";

                TDBCboVoucherTypeID2.SelectedValue = "PC";
                TDBCboEmployeeID2.Text = FRM.UserName;

                TDBCboVoucherTypeID3.SelectedValue = "PN";
                TDBCboCurrencyID3.SelectedValue = "VND";
            }
            if(!_isNew)
            {
                tabControl1.Refresh();
                loadDATA_Edit();
                loadDATA_Edit2();
                loadDATA_Edit3();                
            }                
            
        }

        void loadDATA_Edit()
        {
            sql = "Select * , tb0054.IsSource,tb0054.IsLimitDate,tb0054.IsLocation, tb0054.IsStocked, tb0054.AccountID as IsDebitAccountID";
            sql += " From tb0191   Left Join tb0054 On tb0191.InventoryID = tb0054.InventoryID   ";
            sql += " Where VoucherID = '" + _VoucherID + "' And TransactionTypeID = 'T03' order by Orders";
            DataTable dtT = FRM.GetDataTable(sql);
            if (dtT == null)
            {
                DLL02.Info("Bảng dữ liệu không tồn tại hoặc mất kết nối cơ sở dữ liệu\nVui lòng thử lại");
                Close();
                return;
            }
            else if (dtT.Rows.Count == 0)
            {
                DLL02.Info("Phiếu bán hàng này không tồn tại!");
                Close();
                return;
            }
            GridDB1.PrimaryGrid.DataSource = dtT;

            _BatchID = dtT.Rows[0]["BatchID"].ToString();
            TDBCboVoucherTypeID.Text = dtT.Rows[0]["VoucherTypeID"].ToString();
            txtVoucherNo.Text = dtT.Rows[0]["VoucherNo"].ToString();
            txtVDescription.Text = dtT.Rows[0]["VDescription"].ToString();
            TDBCboCurrencyID.SelectedValue = dtT.Rows[0]["CurrencyID"].ToString();
            DateTime dateT;
            dtpVoucherDate.Value = DateTime.TryParse(dtT.Rows[0]["VoucherDate"].ToString(), out dateT) ? DateTime.Parse(dtT.Rows[0]["VoucherDate"].ToString()) : DateTime.Now;
            dtpInvoiceDate.Value = DateTime.TryParse(dtT.Rows[0]["InvoiceDate"].ToString(), out dateT) ? DateTime.Parse(dtT.Rows[0]["InvoiceDate"].ToString()) : DateTime.Now;
            if (DateTime.TryParse(dtT.Rows[0]["DueDate"].ToString(), out dateT)) { dtpDueDate.Value = dateT; dtpDueDate.Checked = true; }
            txtTypeVoice.Text = dtT.Rows[0]["TypeVoice"].ToString();
            txtSerial.Text = dtT.Rows[0]["Serial"].ToString();
            txtInvoiceNo.Text = dtT.Rows[0]["InvoiceNo"].ToString();
            TDBCboVATTypeID.SelectedValue = dtT.Rows[0]["VATTypeID"].ToString();
            txtExchangeRate.Text = dtT.Rows[0]["ExchangeRate"].ToString();
            TDBCboObjectID.SelectedValue = dtT.Rows[0]["ObjectID"].ToString();
            TDBCboVATObjectID.SelectedValue = dtT.Rows[0]["VATObjectID"].ToString();
            txtVATNo.Text = dtT.Rows[0]["VATNo"].ToString();
            txtBDescription.Text = dtT.Rows[0]["BDescription"].ToString();
            TDBCboPaymentTermID.Text = dtT.Rows[0]["PaymentTermID"].ToString();
            chkIsStock.Checked = dtT.Rows[0]["IsStock"].ToString() == "1" ? true : false;

            sql = string.Format("Select * From tb0191 Where VoucherID = '{0}' And TransactionTypeID = 'T13' ", _VoucherID);
            dtT = FRM.GetDataTable(sql);
            if (dtT.Rows.Count > 0)
            {
                chkVAT.Checked = true;

                TDBCboObjectIDVAT.SelectedValue = dtT.Rows[0]["ObjectID"].ToString();
                TDBCboDebitAccountID.SelectedValue = dtT.Rows[0]["DebitAccountID"].ToString();
                TDBCboCreditAccountID.SelectedValue = dtT.Rows[0]["CreditAccountID"].ToString();
                TDBCboVATGroupID.SelectedValue = dtT.Rows[0]["VATGroupID"].ToString();
                txtTDescription.Text = dtT.Rows[0]["TDescription"].ToString();
                txtVATAmount.Text = dtT.Rows[0]["OriginalAmount"].ToString();
                txtVATConvertedAmount.Text = dtT.Rows[0]["OriginalAmount"].ToString();
            }

            if (_isDuplicate)
            {
                //_isNew = true;
                TDBCboVoucherTypeID.Enabled = true;
                txtVoucherNo.Enabled = true;
                DLL01.Get_VoucherNo(ref igb, FRM.ConnectString, TDBCboVoucherTypeID.Text, txtVoucherNo, "tb0191", FRM.Month, FRM.Year, FRM.DivisionID);
            }
            GridDB1.Update();
            Cal_Price();
        }

        void loadDATA_Edit2()
        {
            sql = "Select * , tb0054.IsSource,tb0054.IsLimitDate,tb0054.IsLocation, tb0054.IsStocked, tb0054.AccountID as IsDebitAccountID";
            sql += " From tb0191   Left Join tb0054 On tb0191.InventoryID = tb0054.InventoryID   ";
            sql += " Where VoucherID = '" + _VoucherID + "' And TransactionTypeID = 'T23' order by Orders";
            DataTable dtT = FRM.GetDataTable(sql);
            if (dtT != null)
            {
                if(dtT.Rows.Count>0)
                {
                    GridDB2.PrimaryGrid.DataSource = dtT;

                    TDBCboVoucherTypeID2.Text = dtT.Rows[0]["VoucherTypeID"].ToString();
                    txtVoucherNo2.Text = dtT.Rows[0]["VoucherNo"].ToString();
                    txtDescription2.Text = dtT.Rows[0]["VDescription"].ToString();
                    TDBCboEmployeeID2.Text = dtT.Rows[0]["EmployeeID"].ToString();
                    DateTime dateT;
                    dtpVoucherDate2.Value = DateTime.TryParse(dtT.Rows[0]["VoucherDate"].ToString(), out dateT) ? DateTime.Parse(dtT.Rows[0]["VoucherDate"].ToString()) : DateTime.Now;

                }
            }
            
            if (_isDuplicate)
            {
                _isNew = true;
                TDBCboEmployeeID2.Enabled = true;
                txtVoucherNo2.Enabled = true;
                DLL01.Get_VoucherNo(ref igb2, FRM.ConnectString, TDBCboVoucherTypeID2.Text, txtVoucherNo2, "tb0191", FRM.Month, FRM.Year, FRM.DivisionID);
            }
            GridDB2.Update();
            tabControl1.SelectTab(1);
            Application.DoEvents();
            tabControl1.SelectTab(0);
            Cal_Price2();
            txtExpenseConvertedAmount.Value = double.Parse(lblTotal2.Text);
        }

        void loadDATA_Edit3()
        {
            sql = "Select * , tb0054.IsSource,tb0054.IsLimitDate,tb0054.IsLocation, tb0054.IsStocked, tb0054.AccountID as IsDebitAccountID";
            sql += " From tb0191   Left Join tb0054 On tb0191.InventoryID = tb0054.InventoryID   ";
            sql += " Where VoucherID = '" + _VoucherID + "' And TransactionTypeID = 'T33' order by Orders";
            DataTable dtT = FRM.GetDataTable(sql);
            if (dtT != null)
            {
                if(dtT.Rows.Count>0)
                {
                    GridDB3.PrimaryGrid.DataSource = dtT;

                    TDBCboVoucherTypeID3.Text = dtT.Rows[0]["VoucherTypeID"].ToString();
                    txtVoucherNo3.Text = dtT.Rows[0]["VoucherNo"].ToString();
                    txtDescription3.Text = dtT.Rows[0]["VDescription"].ToString();
                    TDBCboCurrencyID3.SelectedValue = dtT.Rows[0]["CurrencyID"].ToString();
                    DateTime dateT;
                    dtpVoucherDate3.Value = DateTime.TryParse(dtT.Rows[0]["VoucherDate"].ToString(), out dateT) ? DateTime.Parse(dtT.Rows[0]["VoucherDate"].ToString()) : DateTime.Now;
                    dtpPickerInvoiceDate3.Value = DateTime.TryParse(dtT.Rows[0]["InvoiceDate"].ToString(), out dateT) ? DateTime.Parse(dtT.Rows[0]["InvoiceDate"].ToString()) : DateTime.Now;
                    txtTypeVoice3.Text = dtT.Rows[0]["TypeVoice"].ToString();
                    txtSerial3.Text = dtT.Rows[0]["Serial"].ToString();
                    txtInvoiceNo3.Text = dtT.Rows[0]["InvoiceNo"].ToString();
                    TDBCboVATTypeID3.SelectedValue = dtT.Rows[0]["VATTypeID"].ToString();
                    txtExchangeRate3.Text = dtT.Rows[0]["ExchangeRate"].ToString();
                    TDBCboObjectID3.SelectedValue = dtT.Rows[0]["ObjectID"].ToString();
                    txtTypeVoice3.Text = dtT.Rows[0]["TypeVoice"].ToString();
                }
            }
            

            if (_isDuplicate)
            {
                _isNew = true;
                TDBCboVoucherTypeID3.Enabled = true;
                txtVoucherNo3.Enabled = true;
                DLL01.Get_VoucherNo(ref igb3, FRM.ConnectString, TDBCboVoucherTypeID3.Text, txtVoucherNo3, "tb0191", FRM.Month, FRM.Year, FRM.DivisionID);
            }
            GridDB3.Update();
            Cal_Price3();
        }

        void loadDATA_Combo()
        {
            GUI.ChangeDateFormat(dtpVoucherDate, FRM.SystemDateFormat);
            GUI.ChangeDateFormat(dtpInvoiceDate, FRM.SystemDateFormat);
            GUI.ChangeDateFormat(dtpDueDate, FRM.SystemDateFormat);
            if (_isNew)
            {
                dtpVoucherDate.Value = FRM.DateDue;
                dtpInvoiceDate.Value = FRM.DateDue;
                dtpDueDate.Value = FRM.DateDue;
            }

            if(_isNew||_isDuplicate)
            {
                // loại chứng từ 
                sql = string.Format("Select * From tb0027 Where Disabled =0 and VoucherGroupID in ('21' ,'99') AND CHARINDEX('{0}',GroupShow)>0 Order by VoucherTypeID", FRM.ID_Group);
                TDBCboVoucherTypeID.DataSource = FRM.GetDataTable(sql);
            }
            
            // loại tiền 
            sql = "Select * From tb0024 Where Disabled =0 Order by CurrencyID";
            TDBCboCurrencyID.DataSource = FRM.GetDataTable(sql);
            
            // đối tượng
            TDBCboObjectID.DataSource = FRM.dt_Object;
            TDBCboObjectIDVAT.DataSource = FRM.dt_Object;
            TDBCboVATObjectID.DataSource = FRM.dt_Object;

            // Tài khoản có
            sql = string.Format("Select * From tb0025 Where Disabled =0 and IsNotShow =0 and GroupID in ('G04','G03','G01') AND CHARINDEX('{0}',GroupShow)>0 Order by AccountID", FRM.ID_Group);
            TDBCboCreditAccountID.DataSource = FRM.GetDataTable(sql);

            // Tài khoản nợ
            sql = string.Format("Select * From tb0025 Where Disabled =0 and IsNotShow =0 and GroupID = 'G03' AND CHARINDEX('{0}',GroupShow)>0 Order by AccountID",FRM.ID_Group);
            TDBCboDebitAccountID.DataSource = FRM.GetDataTable(sql);

            // loại hóa đơn
            sql = "Select * From tb0029 Where Disabled =0  and IsVATIn = 1 Order by VATTypeID";
            TDBCboVATTypeID.DataSource = FRM.GetDataTable(sql);

            // nhóm thuế
            sql = "Select * From tb0030 Where Disabled =0 Order by VATGroupID";
            TDBCboVATGroupID.DataSource = FRM.GetDataTable(sql);

            // mặt hàng GRID
            SCBX.GridMultiComboBox clInventoryID = (SCBX.GridMultiComboBox)GridDB1.PrimaryGrid.Columns["clInventoryID"].EditControl;
            clInventoryID.ColumnWidth = new string[] { "80", "170", "100", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0" };
            clInventoryID.SourceDataHeader = new string[] { "Mã hàng", "Tên hàng", "Mã ĐV Tính" };
            clInventoryID.SourceDataString = new string[] { "InventoryID", "InventoryName", "UnitID", "AccountID", "SalesAccountID", "I01ID", "I02ID", "I03ID", "I04ID", "I05ID" };
            clInventoryID.StringFilter = "InventoryID LIKE '{0}%' OR InventoryName LIKE '%{0}%'";
            clInventoryID.DisplayColumnNo = 0;
            clInventoryID.DataSource = FRM.dt_Inventory;

            // tài khoản GRID
            sql = string.Format("Select * From tb0025 Where Disabled = 0 and IsNotShow =0  And GroupID<>'G00' AND CHARINDEX('{0}',GroupShow)>0 Order by AccountID",FRM.ID_Group);
            DataTable dt_tb0025_CreditAccount = FRM.GetDataTable(sql); ;

            SCBX.GridMultiComboBox DebitAccountID = (SCBX.GridMultiComboBox)GridDB1.PrimaryGrid.Columns["clDebitAccountID"].EditControl;
            DebitAccountID.ColumnWidth = new string[] { "90", "200" };
            DebitAccountID.SourceDataHeader = new string[] { "Mã TK Nợ", "Tên TK Nợ" };
            DebitAccountID.SourceDataString = new string[] { "AccountID", "AccountName" };
            DebitAccountID.StringFilter = "AccountID LIKE '{0}%'";
            DebitAccountID.DisplayColumnNo = 0;
            DebitAccountID.DataSource = dt_tb0025_CreditAccount;

            SCBX.GridMultiComboBox CreditAccountID = (SCBX.GridMultiComboBox)GridDB1.PrimaryGrid.Columns["clCreditAccountID"].EditControl;
            CreditAccountID.ColumnWidth = new string[] { "90", "200" };
            CreditAccountID.SourceDataHeader = new string[] { "Mã TK Có", "Tên TK Có" };
            CreditAccountID.SourceDataString = new string[] { "AccountID", "AccountName" };
            CreditAccountID.StringFilter = "AccountID LIKE '{0}%'";
            CreditAccountID.DisplayColumnNo = 0;
            CreditAccountID.DataSource = dt_tb0025_CreditAccount;

            // khoản mục [Mã phân tích]
            sql = "Select * From tb0031 Where Disabled =0 And AnaTypeID = 'A01' Order by AnaID";
            SCBX.GridMultiComboBox clAna01ID = (SCBX.GridMultiComboBox)GridDB1.PrimaryGrid.Columns["clAna01ID"].EditControl;
            clAna01ID.ColumnWidth = new string[] { "100", "150", "150" };
            clAna01ID.SourceDataHeader = new string[] { "Mã phân tích", "Tên phân tích", "Ghi chú" };
            clAna01ID.SourceDataString = new string[] { "AnaID", "AnaName", "Notes" };
            clAna01ID.StringFilter = "AnaID LIKE '{0}%' OR AnaName LIKE '%{0}%'";
            clAna01ID.DisplayColumnNo = 0;
            clAna01ID.DataSource = FRM.GetDataTable(sql);

            sql = "Select * From tb0031 Where Disabled =0 And AnaTypeID = 'A02' Order by AnaID";
            SCBX.GridMultiComboBox clAna02ID = (SCBX.GridMultiComboBox)GridDB1.PrimaryGrid.Columns["clAna02ID"].EditControl;
            clAna02ID.ColumnWidth = new string[] { "100", "150", "150" };
            clAna02ID.SourceDataHeader = new string[] { "Mã phân tích", "Tên phân tích", "Ghi chú" };
            clAna02ID.SourceDataString = new string[] { "AnaID", "AnaName", "Notes" };
            clAna02ID.StringFilter = "AnaID LIKE '{0}%' OR AnaName LIKE '%{0}%'";
            clAna02ID.DisplayColumnNo = 0;
            clAna02ID.DataSource = FRM.GetDataTable(sql);

            sql = "Select * From tb0031 Where Disabled =0 And AnaTypeID = 'A03' Order by AnaID";
            SCBX.GridMultiComboBox clAna03ID = (SCBX.GridMultiComboBox)GridDB1.PrimaryGrid.Columns["clAna03ID"].EditControl;
            clAna03ID.ColumnWidth = new string[] { "100", "150", "150" };
            clAna03ID.SourceDataHeader = new string[] { "Mã phân tích", "Tên phân tích", "Ghi chú" };
            clAna03ID.SourceDataString = new string[] { "AnaID", "AnaName", "Notes" };
            clAna03ID.StringFilter = "AnaID LIKE '{0}%' OR AnaName LIKE '%{0}%'";
            clAna03ID.DisplayColumnNo = 0;
            clAna03ID.DataSource = FRM.GetDataTable(sql);

            sql = "Select * From tb0031 Where Disabled =0 And AnaTypeID = 'A04' Order by AnaID";
            SCBX.GridMultiComboBox clAna04ID = (SCBX.GridMultiComboBox)GridDB1.PrimaryGrid.Columns["clAna04ID"].EditControl;
            clAna04ID.ColumnWidth = new string[] { "100", "150", "150" };
            clAna04ID.SourceDataHeader = new string[] { "Mã phân tích", "Tên phân tích", "Ghi chú" };
            clAna04ID.SourceDataString = new string[] { "AnaID", "AnaName", "Notes" };
            clAna04ID.StringFilter = "AnaID LIKE '{0}%' OR AnaName LIKE '%{0}%'";
            clAna04ID.DisplayColumnNo = 0;
            clAna04ID.DataSource = FRM.GetDataTable(sql);

            sql = "Select * From tb0031 Where Disabled =0 And AnaTypeID = 'A05' Order by AnaID";
            SCBX.GridMultiComboBox clAna05ID = (SCBX.GridMultiComboBox)GridDB1.PrimaryGrid.Columns["clAna05ID"].EditControl;
            clAna05ID.ColumnWidth = new string[] { "100", "150", "150" };
            clAna05ID.SourceDataHeader = new string[] { "Mã phân tích", "Tên phân tích", "Ghi chú" };
            clAna05ID.SourceDataString = new string[] { "AnaID", "AnaName", "Notes" };
            clAna05ID.StringFilter = "AnaID LIKE '{0}%' OR AnaName LIKE '%{0}%'";
            clAna05ID.DisplayColumnNo = 0;
            clAna05ID.DataSource = FRM.GetDataTable(sql);

            // điều kiện thanh toán
            sql = "SELECT PaymentTermID,PaymentTermName,Duedays,Duetype FROM tb0051 WHERE Disabled=0 ORDER BY PaymentTermID";
            TDBCboPaymentTermID.DataSource = FRM.dt_GET(ref FRM.dt_PaymentTerm, sql);

        }

        void loadDATA_Combo2()
        {
            GUI.ChangeDateFormat(dtpVoucherDate2, FRM.SystemDateFormat);
            dtpVoucherDate2.Value = FRM.DateDue;

            // loại chứng từ
            sql = string.Format("Select * From tb0027 Where Disabled =0 AND CHARINDEX('{0}',GroupShow)>0 Order by VoucherTypeID", FRM.ID_Group);
            TDBCboVoucherTypeID2.DataSource = FRM.GetDataTable(sql);                      
            
            // nhân viên
            sql = string.Format("Select tb0040.ID,tb0040.EmployeeID, tb0040.FullName From tb0040 LEFT JOIN tb0071 ON tb0040.EmployeeID = tb0071.UserID LEFT JOIN tb0070 ON tb0070.GroupID = tb0071.GroupID Where tb0040.Disabled =0 and DivisionID = '{0}' and CHARINDEX('@'+CAST(tb0070.ID AS VARCHAR(20)),'{1}') > 0 Order by EmployeeID", FRM.DivisionID, FRM.ID_GroupList);
            TDBCboEmployeeID2.DataSource = FRM.GetDataTable(sql);

            // loại tiền
            sql = "Select * From tb0024 Where Disabled =0 Order by CurrencyID";
            SCBX.GridMultiComboBox clCurrencyID = (SCBX.GridMultiComboBox)GridDB2.PrimaryGrid.Columns["clCurrencyID"].EditControl;
            clCurrencyID.ColumnWidth = new string[] { "120", "150","0" };
            clCurrencyID.SourceDataHeader = new string[] { "Mã loại tiền", "Tên loại tiền"};
            clCurrencyID.SourceDataString = new string[] { "CurrencyID", "CurrencyName", "ExchangeRate"};
            clCurrencyID.StringFilter = "CurrencyID LIKE '{0}%' OR CurrencyName LIKE '%{0}%'";
            clCurrencyID.DisplayColumnNo = 0;
            clCurrencyID.DataSource = FRM.GetDataTable(sql);

            // tài khoản nợ
            sql = string.Format("Select * From tb0025 Where Disabled =0 and IsNotShow =0  and  GroupID not in ('G00') AND CHARINDEX('{0}',GroupShow)>0 Order by AccountID", FRM.ID_Group);
            DataTable tb_0025 = FRM.GetDataTable(sql);
            SCBX.GridMultiComboBox clDebitAccountID = (SCBX.GridMultiComboBox)GridDB2.PrimaryGrid.Columns["clDebitAccountID"].EditControl;
            clDebitAccountID.ColumnWidth = new string[] { "120", "150" };
            clDebitAccountID.SourceDataHeader = new string[] { "Mã tài khoản", "Tên tài khoản" };
            clDebitAccountID.SourceDataString = new string[] { "AccountID", "AccountName" };
            clDebitAccountID.StringFilter = "AccountID LIKE '{0}%' OR AccountName LIKE '%{0}%'";
            clDebitAccountID.DisplayColumnNo = 0;
            clDebitAccountID.DataSource = tb_0025;

            //tài khoản có
            SCBX.GridMultiComboBox clCreditAccountID= (SCBX.GridMultiComboBox)GridDB2.PrimaryGrid.Columns["clCreditAccountID"].EditControl;
            clCreditAccountID.ColumnWidth = new string[] { "120", "150" };
            clCreditAccountID.SourceDataHeader = new string[] { "Mã tài khoản", "Tên tài khoản" };
            clCreditAccountID.SourceDataString = new string[] { "AccountID", "AccountName" };
            clCreditAccountID.StringFilter = "AccountID LIKE '{0}%' OR AccountName LIKE '%{0}%'";
            clCreditAccountID.DisplayColumnNo = 0;
            clCreditAccountID.DataSource = tb_0025;

            // đối tượng
            sql = "Select * From tb0045 Where Disabled =0 Order by ObjectID";
            SCBX.GridMultiComboBox clObjectID = (SCBX.GridMultiComboBox)GridDB2.PrimaryGrid.Columns["clObjectID"].EditControl;
            clObjectID.ColumnWidth = new string[] { "120", "200" };
            clObjectID.SourceDataHeader = new string[] { "Mã đối tượng", "Tên đối tượng" };
            clObjectID.SourceDataString = new string[] { "ObjectID", "ObjectName" };
            clObjectID.StringFilter = "ObjectID LIKE '{0}%' OR ObjectName LIKE '%{0}%'";
            clObjectID.DisplayColumnNo = 0;
            clObjectID.DataSource = FRM.GetDataTable(sql);

            // loại hóa đơn
            sql = "Select * From tb0029 Where Disabled =0  Order by VATTypeID";
            SCBX.GridMultiComboBox clVATTypeID = (SCBX.GridMultiComboBox)GridDB2.PrimaryGrid.Columns["clVATTypeID"].EditControl;
            clVATTypeID.ColumnWidth = new string[] { "150", "170" };
            clVATTypeID.SourceDataHeader = new string[] { "Mã loại hóa đơn", "Tên loại hóa đơn" };
            clVATTypeID.SourceDataString = new string[] { "VATTypeID", "VATTypeName" };
            clVATTypeID.StringFilter = "VATTypeID LIKE '{0}%' OR VATTypeName LIKE '%{0}%'";
            clVATTypeID.DisplayColumnNo = 0;
            clVATTypeID.DataSource = FRM.GetDataTable(sql);

            // nhóm thuế
            sql = "Select * From tb0030 Where Disabled =0  Order by VATGroupID";
            SCBX.GridMultiComboBox clVATGroupID = (SCBX.GridMultiComboBox)GridDB2.PrimaryGrid.Columns["clVATGroupID"].EditControl;
            clVATGroupID.ColumnWidth = new string[] { "150", "170" };
            clVATGroupID.SourceDataHeader = new string[] { "Mã nhóm thuế", "Tên nhóm thuế" };
            clVATGroupID.SourceDataString = new string[] { "VATGroupID", "VATGroupName" };
            clVATGroupID.StringFilter = "VATGroupID LIKE '{0}%' OR VATGroupName LIKE '%{0}%'";
            clVATGroupID.DisplayColumnNo = 0;
            clVATGroupID.DataSource = FRM.GetDataTable(sql);

            // khoản mục [Mã phân tích]
            sql = "Select * From tb0031 Where Disabled =0 And AnaTypeID = 'A01' Order by AnaID";
            SCBX.GridMultiComboBox clAna01ID = (SCBX.GridMultiComboBox)GridDB2.PrimaryGrid.Columns["clAna01ID"].EditControl;
            clAna01ID.ColumnWidth = new string[] { "100", "150", "150" };
            clAna01ID.SourceDataHeader = new string[] { "Mã phân tích", "Tên phân tích", "Ghi chú" };
            clAna01ID.SourceDataString = new string[] { "AnaID", "AnaName", "Notes" };
            clAna01ID.StringFilter = "AnaID LIKE '{0}%' OR AnaName LIKE '%{0}%'";
            clAna01ID.DisplayColumnNo = 0;
            clAna01ID.DataSource = FRM.GetDataTable(sql);

            sql = "Select * From tb0031 Where Disabled =0 And AnaTypeID = 'A02' Order by AnaID";
            SCBX.GridMultiComboBox clAna02ID = (SCBX.GridMultiComboBox)GridDB2.PrimaryGrid.Columns["clAna02ID"].EditControl;
            clAna02ID.ColumnWidth = new string[] { "100", "150", "150" };
            clAna02ID.SourceDataHeader = new string[] { "Mã phân tích", "Tên phân tích", "Ghi chú" };
            clAna02ID.SourceDataString = new string[] { "AnaID", "AnaName", "Notes" };
            clAna02ID.StringFilter = "AnaID LIKE '{0}%' OR AnaName LIKE '%{0}%'";
            clAna02ID.DisplayColumnNo = 0;
            clAna02ID.DataSource = FRM.GetDataTable(sql);

            sql = "Select * From tb0031 Where Disabled =0 And AnaTypeID = 'A03' Order by AnaID";
            SCBX.GridMultiComboBox clAna03ID = (SCBX.GridMultiComboBox)GridDB2.PrimaryGrid.Columns["clAna03ID"].EditControl;
            clAna03ID.ColumnWidth = new string[] { "100", "150", "150" };
            clAna03ID.SourceDataHeader = new string[] { "Mã phân tích", "Tên phân tích", "Ghi chú" };
            clAna03ID.SourceDataString = new string[] { "AnaID", "AnaName", "Notes" };
            clAna03ID.StringFilter = "AnaID LIKE '{0}%' OR AnaName LIKE '%{0}%'";
            clAna03ID.DisplayColumnNo = 0;
            clAna03ID.DataSource = FRM.GetDataTable(sql);

            sql = "Select * From tb0031 Where Disabled =0 And AnaTypeID = 'A04' Order by AnaID";
            SCBX.GridMultiComboBox clAna04ID = (SCBX.GridMultiComboBox)GridDB2.PrimaryGrid.Columns["clAna04ID"].EditControl;
            clAna04ID.ColumnWidth = new string[] { "100", "150", "150" };
            clAna04ID.SourceDataHeader = new string[] { "Mã phân tích", "Tên phân tích", "Ghi chú" };
            clAna04ID.SourceDataString = new string[] { "AnaID", "AnaName", "Notes" };
            clAna04ID.StringFilter = "AnaID LIKE '{0}%' OR AnaName LIKE '%{0}%'";
            clAna04ID.DisplayColumnNo = 0;
            clAna04ID.DataSource = FRM.GetDataTable(sql);

            sql = "Select * From tb0031 Where Disabled =0 And AnaTypeID = 'A05' Order by AnaID";
            SCBX.GridMultiComboBox clAna05ID = (SCBX.GridMultiComboBox)GridDB2.PrimaryGrid.Columns["clAna05ID"].EditControl;
            clAna05ID.ColumnWidth = new string[] { "100", "150", "150" };
            clAna05ID.SourceDataHeader = new string[] { "Mã phân tích", "Tên phân tích", "Ghi chú" };
            clAna05ID.SourceDataString = new string[] { "AnaID", "AnaName", "Notes" };
            clAna05ID.StringFilter = "AnaID LIKE '{0}%' OR AnaName LIKE '%{0}%'";
            clAna05ID.DisplayColumnNo = 0;
            clAna05ID.DataSource = FRM.GetDataTable(sql);

        }

        void loadDATA_Combo3()
        {
            GUI.ChangeDateFormat(dtpVoucherDate3, FRM.SystemDateFormat);
            GUI.ChangeDateFormat(dtpPickerInvoiceDate3, FRM.SystemDateFormat);
            if (_isNew)
            {
                dtpVoucherDate3.Value = FRM.DateDue;
                dtpPickerInvoiceDate3.Value = FRM.DateDue;
            }

            // loại chứng từ
            sql = string.Format("Select * From tb0027 Where Disabled  = 0 AND CHARINDEX('{0}',GroupShow)>0 Order by VoucherTypeID", FRM.ID_Group);
            TDBCboVoucherTypeID3.DataSource = FRM.GetDataTable(sql);      

            // loại tiền
            sql ="Select * From tb0024 Where Disabled =0 Order by CurrencyID";
            TDBCboCurrencyID3.DataSource = FRM.GetDataTable(sql);

            // đối tượng 
            sql = "Select * From tb0045 Where Disabled =0 Order by ObjectID";
            TDBCboObjectID3.DataSource = FRM.GetDataTable(sql);

            // loại hóa đơn
            sql = "Select * From tb0029 Where Disabled =0  and IsVATIn = 1 Order by VATTypeID";
            TDBCboVATTypeID3.DataSource = FRM.GetDataTable(sql);

            // tài khoản có
            sql = string.Format("Select * From tb0025 Where Disabled = 0 and IsNotShow =0  And GroupID<>'G00' AND CHARINDEX('{0}',GroupShow)>0 Order by AccountID", FRM.ID_Group);
            SCBX.GridMultiComboBox clCreditAccountID = (SCBX.GridMultiComboBox)GridDB3.PrimaryGrid.Columns["clCreditAccountID"].EditControl;
            clCreditAccountID.ColumnWidth = new string[] { "120", "150" };
            clCreditAccountID.SourceDataHeader = new string[] { "Mã tài khoản", "Tên tài khoản" };
            clCreditAccountID.SourceDataString = new string[] { "AccountID", "AccountName" };
            clCreditAccountID.StringFilter = "AccountID LIKE '{0}%' OR AccountName LIKE '%{0}%'";
            clCreditAccountID.DisplayColumnNo = 0;
            clCreditAccountID.DataSource = FRM.GetDataTable(sql);

            // tài khoản nợ
            sql = string.Format("Select * From tb0025 Where Disabled =0 and IsNotShow =0  and  GroupID<>'G00' AND CHARINDEX('{0}',GroupShow)>0 Order by AccountID", FRM.ID_Group);
            DataTable tb_0025 = FRM.GetDataTable(sql);
            SCBX.GridMultiComboBox clDebitAccountID = (SCBX.GridMultiComboBox)GridDB3.PrimaryGrid.Columns["clDebitAccountID"].EditControl;
            clDebitAccountID.ColumnWidth = new string[] { "120", "150" };
            clDebitAccountID.SourceDataHeader = new string[] { "Mã tài khoản", "Tên tài khoản" };
            clDebitAccountID.SourceDataString = new string[] { "AccountID", "AccountName" };
            clDebitAccountID.StringFilter = "AccountID LIKE '{0}%' OR AccountName LIKE '%{0}%'";
            clDebitAccountID.DisplayColumnNo = 0;
            clDebitAccountID.DataSource = FRM.GetDataTable(sql);

            // khoản mục [Mã phân tích]
            sql = "Select * From tb0031 Where Disabled =0 And AnaTypeID = 'A01' Order by AnaID";
            SCBX.GridMultiComboBox clAna01ID = (SCBX.GridMultiComboBox)GridDB3.PrimaryGrid.Columns["clAna01ID"].EditControl;
            clAna01ID.ColumnWidth = new string[] { "100", "150", "150" };
            clAna01ID.SourceDataHeader = new string[] { "Mã phân tích", "Tên phân tích", "Ghi chú" };
            clAna01ID.SourceDataString = new string[] { "AnaID", "AnaName", "Notes" };
            clAna01ID.StringFilter = "AnaID LIKE '{0}%' OR AnaName LIKE '%{0}%'";
            clAna01ID.DisplayColumnNo = 0;
            clAna01ID.DataSource = FRM.GetDataTable(sql);

            sql = "Select * From tb0031 Where Disabled =0 And AnaTypeID = 'A02' Order by AnaID";
            SCBX.GridMultiComboBox clAna02ID = (SCBX.GridMultiComboBox)GridDB3.PrimaryGrid.Columns["clAna02ID"].EditControl;
            clAna02ID.ColumnWidth = new string[] { "100", "150", "150" };
            clAna02ID.SourceDataHeader = new string[] { "Mã phân tích", "Tên phân tích", "Ghi chú" };
            clAna02ID.SourceDataString = new string[] { "AnaID", "AnaName", "Notes" };
            clAna02ID.StringFilter = "AnaID LIKE '{0}%' OR AnaName LIKE '%{0}%'";
            clAna02ID.DisplayColumnNo = 0;
            clAna02ID.DataSource = FRM.GetDataTable(sql);

            sql = "Select * From tb0031 Where Disabled =0 And AnaTypeID = 'A03' Order by AnaID";
            SCBX.GridMultiComboBox clAna03ID = (SCBX.GridMultiComboBox)GridDB3.PrimaryGrid.Columns["clAna03ID"].EditControl;
            clAna03ID.ColumnWidth = new string[] { "100", "150", "150" };
            clAna03ID.SourceDataHeader = new string[] { "Mã phân tích", "Tên phân tích", "Ghi chú" };
            clAna03ID.SourceDataString = new string[] { "AnaID", "AnaName", "Notes" };
            clAna03ID.StringFilter = "AnaID LIKE '{0}%' OR AnaName LIKE '%{0}%'";
            clAna03ID.DisplayColumnNo = 0;
            clAna03ID.DataSource = FRM.GetDataTable(sql);

            sql = "Select * From tb0031 Where Disabled =0 And AnaTypeID = 'A04' Order by AnaID";
            SCBX.GridMultiComboBox clAna04ID = (SCBX.GridMultiComboBox)GridDB3.PrimaryGrid.Columns["clAna04ID"].EditControl;
            clAna04ID.ColumnWidth = new string[] { "100", "150", "150" };
            clAna04ID.SourceDataHeader = new string[] { "Mã phân tích", "Tên phân tích", "Ghi chú" };
            clAna04ID.SourceDataString = new string[] { "AnaID", "AnaName", "Notes" };
            clAna04ID.StringFilter = "AnaID LIKE '{0}%' OR AnaName LIKE '%{0}%'";
            clAna04ID.DisplayColumnNo = 0;
            clAna04ID.DataSource = FRM.GetDataTable(sql);

            sql = "Select * From tb0031 Where Disabled =0 And AnaTypeID = 'A05' Order by AnaID";
            SCBX.GridMultiComboBox clAna05ID = (SCBX.GridMultiComboBox)GridDB3.PrimaryGrid.Columns["clAna05ID"].EditControl;
            clAna05ID.ColumnWidth = new string[] { "100", "150", "150" };
            clAna05ID.SourceDataHeader = new string[] { "Mã phân tích", "Tên phân tích", "Ghi chú" };
            clAna05ID.SourceDataString = new string[] { "AnaID", "AnaName", "Notes" };
            clAna05ID.StringFilter = "AnaID LIKE '{0}%' OR AnaName LIKE '%{0}%'";
            clAna05ID.DisplayColumnNo = 0;
            clAna05ID.DataSource = FRM.GetDataTable(sql);

        }

        private void TDBCboVoucherTypeID_SelectedIndexChanged(object sender, EventArgs e)
        {
            DLL01.Get_VoucherNo(ref igb, FRM.ConnectString, TDBCboVoucherTypeID.Text, txtVoucherNo, "tb0191", FRM.Month, FRM.Year, FRM.DivisionID);
        
        }

        private void cmdClose_Click(object sender, EventArgs e)
        {
            if (_isNew||_isDuplicate) { (Application.OpenForms["frm0244"] as frm0244).CloseTab(); }
            else { Close(); }
        }

        private void TDBCboObjectIDVAT_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtObjectNameVAT.Text = TDBCboObjectID.SelectedItem != null ? TDBCboObjectID.SelectedItem.ItemData[1] : "";
        }

        private void chkVAT_CheckedChanged(object sender, EventArgs e)
        {
            fraVAT.Enabled = chkVAT.Checked;
            if(!fraVAT.Enabled)
            {
                TDBCboObjectIDVAT.Clear();
                TDBCboDebitAccountID.Clear();
                TDBCboCreditAccountID.Clear();
                TDBCboVATGroupID.Clear();
                txtVATAmount.Value = 0.0;
                txtVATConvertedAmount.Value = 0.0;
                txtTDescription.Text = "";
            }
        }

        private void TDBCboObjectID_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (TDBCboObjectID.SelectedItem != null)
            {
                txtObjectName.Text = TDBCboObjectID.SelectedItem.ItemData[1];
                TDBCboVATObjectID.SelectedValue = txtObjectName.Text;
                if (chkVAT.Checked) { TDBCboObjectIDVAT.SelectedValue = txtObjectName.Text; }
            }
            else
            {
                txtObjectName.Text = "";
            }
        }

        private void TDBCboVATObjectID_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (TDBCboVATObjectID.SelectedItem != null)
            {
                txtVATObjectName.Text = TDBCboVATObjectID.SelectedItem.ItemData[1];
                txtVATObjectAddress.Text = TDBCboVATObjectID.SelectedItem.ItemData[2];
            }
            else
            {
                txtVATObjectName.Text = "";
                txtVATObjectAddress.Text = "";
            }
        }

        private void TDBCboPaymentTermID_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtPaymentTermName.Text = TDBCboPaymentTermID.SelectedItem != null ? TDBCboPaymentTermID.SelectedItem.ItemData[1] : "";
        }

        private void TDBCboCurrencyID_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtExchangeRate.Text = TDBCboCurrencyID.SelectedItem != null ? TDBCboCurrencyID.SelectedItem.ItemData[2] : "0";
            txtVATAmount.Value = txtVATConvertedAmount.Value / txtExchangeRate.Value;
            if (GridDB1.PrimaryGrid.Rows.Count > 0) { Cal_Price(); }
        }

        private void txtVATConvertedAmount_KeyUp(object sender, KeyEventArgs e)
        {
            txtVATAmount.Value = txtVATConvertedAmount.Value / txtExchangeRate.Value;
            if (GridDB1.PrimaryGrid.Rows.Count > 0) { Cal_Price(); }
        }

        private void Cal_Price()
        {
            if (txtExchangeRate.Text == null)
            {
                MessageBox.Show("Vui lòng chọn loại tiền!");
                return;
            }
            double Total = 0;
            int Orders = 1;
            _TotalQuantity = 0;
            _TotalImTax = 0;

            for (int i = 0; i < GridDB1.PrimaryGrid.Rows.Count; i++)
            {
                if (GridDB1.PrimaryGrid.GetCell(i, 1).Value != null)
                {                    
                    if (GridDB1.PrimaryGrid.GetCell(i, 1).Value.ToString() == "") { continue; }
                    GridDB1.PrimaryGrid.GetCell(i, 0).Value = Orders;
                    GridDB1.PrimaryGrid.GetCell(i, 6).Value = (GridDB1.PrimaryGrid.GetCell(i, 3).Value == null ? 0.0 : double.Parse(GridDB1.PrimaryGrid.GetCell(i, 3).Value.ToString())) * (GridDB1.PrimaryGrid.GetCell(i, 5).Value == null ? 0.0 : double.Parse(GridDB1.PrimaryGrid.GetCell(i, 5).Value.ToString()));
                    GridDB1.PrimaryGrid.GetCell(i, 7).Value = (GridDB1.PrimaryGrid.GetCell(i, 6).Value == null ? 0.0 : double.Parse(GridDB1.PrimaryGrid.GetCell(i, 6).Value.ToString())) * txtExchangeRate.Value;
                    Total = Total + (GridDB1.PrimaryGrid.GetCell(i, 7).Value == null ? 0.0 : double.Parse(GridDB1.PrimaryGrid.GetCell(i, 7).Value.ToString()));
                    Orders += 1;

                    _TotalImTax += (GridDB1.PrimaryGrid.GetCell(i, 12).Value == null ? 0.0 : double.Parse(GridDB1.PrimaryGrid.GetCell(i, 12).Value.ToString()));
                    _TotalQuantity += (GridDB1.PrimaryGrid.GetCell(i, 3).Value == null ? 0.0 : double.Parse(GridDB1.PrimaryGrid.GetCell(i, 3).Value.ToString()));
                }
                else
                {
                    GridDB1.PrimaryGrid.GetCell(i, 0).Value = null;
                }
            }
            Total += txtVATConvertedAmount.Value;            
            lblTotal.Text = string.Format("{0:#,#.00}", Total);
            txtImTaxConvertedAmount.Value = _TotalImTax;
            _TotalPrice = Total;
            Tranfer_Grid1_Grid3();
        }

        private void Cal_Price2()
        {
            double Total = 0;
            int Orders = 1;
            for (int i = 0; i < GridDB2.PrimaryGrid.Rows.Count; i++)
            {
                if (GridDB2.GetCellVal(i, 1) != null && GridDB2.GetCellVal(i, 2) != null)
                {
                    GridDB2.PrimaryGrid.GetCell(i, 0).Value = Orders;
                    if (GridDB2.PrimaryGrid.GetCell(i, 5).Value==null) { continue; }
                    GridDB2.PrimaryGrid.GetCell(i, 7).Value = (GridDB2.PrimaryGrid.GetCell(i, 6).Value == null ? 0.0 : double.Parse(GridDB2.PrimaryGrid.GetCell(i, 6).Value.ToString())) * (GridDB2.PrimaryGrid.GetCell(i, 5).Value == null ? 0.0 : double.Parse(GridDB2.PrimaryGrid.GetCell(i, 5).Value.ToString()));
                    Total = Total + (GridDB2.PrimaryGrid.GetCell(i, 7).Value == null ? 0.0 : double.Parse(GridDB2.PrimaryGrid.GetCell(i, 7).Value.ToString()));
                    Orders += 1;
                }
                else
                {
                    //GridDB2.PrimaryGrid.Rows[i].Visible = false;
                    GridDB2.PrimaryGrid.GetCell(i, 0).Value = null;
                    GridDB2.PrimaryGrid.GetCell(i, 6).Value = 0.0;
                    GridDB2.PrimaryGrid.GetCell(i, 7).Value = 0.0;
                    continue;
                }
            }
            lblTotal2.Text = string.Format("{0:#,#.00}", Total);
        }

        private void Cal_Price3()
        {
            double Total = 0;
            for (int i = 0; i < GridDB3.PrimaryGrid.Rows.Count; i++)
            {
                if (GridDB3.GetCellVal(i, 0) !=null&& GridDB3.GetCellVal(i, 1)!=null)
                {                 
                    GridDB3.PrimaryGrid.GetCell(i, 3).Value = (GridDB3.PrimaryGrid.GetCell(i, 2).Value == null ? 0.0 : double.Parse(GridDB3.PrimaryGrid.GetCell(i, 2).Value.ToString())) * double.Parse(txtExchangeRate3.Text);
                    Total = Total + (GridDB3.PrimaryGrid.GetCell(i, 3).Value == null ? 0.0 : double.Parse(GridDB3.PrimaryGrid.GetCell(i, 3).Value.ToString()));
                }
                else if (GridDB3.GetCellVal(i, 0) == null && GridDB3.GetCellVal(i, 1)==null)
                {
                    //GridDB2.PrimaryGrid.Rows[i].Visible = false;
                    GridDB3.PrimaryGrid.GetCell(i, 0).Value = null;
                    GridDB3.PrimaryGrid.GetCell(i, 1).Value = null;
                    GridDB3.PrimaryGrid.GetCell(i, 2).Value = 0.0;
                    GridDB3.PrimaryGrid.GetCell(i, 3).Value = 0.0;
                    continue;
                }
            }
            lblTotal3.Text = string.Format("{0:#,#.00}", Total);
        }

        private void Tranfer_Grid1_Grid3()
        {
            //if (GridDB1.PrimaryGrid.Rows.Count < 1) { return; }
            if (_TotalImTax == 0)
            {
                GridDB3.PrimaryGrid.Rows.Clear();
                return;
            }
            TDBCboCurrencyID3.SelectedValue = TDBCboCurrencyID.Text;
            GridDB3.PrimaryGrid.Rows.Clear();
            for(int i=0; i<GridDB1.PrimaryGrid.Rows.Count;i++)
            {
                if (GridDB1.PrimaryGrid.GetCell(i, 1).Value != null && GridDB1.GetCellVal(i, 12) != null)
                {
                    if (double.Parse(GridDB1.GetCellVal(i, 12)) <= 0) { continue; }
                    GridRow gr = GridDB3.PrimaryGrid.InsertRow(GridDB3.PrimaryGrid.Rows.Count);
                    gr.Cells[0].Value = GridDB1.GetCellVal(i, 8);
                    gr.Cells[1].Value = "3333";
                    gr.Cells[2].Value = GridDB1.GetCellVal(i, 12);
                    gr.Cells[3].Value = double.Parse(GridDB1.GetCellVal(i, 12)) * txtExchangeRate3.Value;
                }
            }
            lblTotal3.Text = string.Format("{0:#,#.00}", _TotalImTax);
        }

        private void GridDB1_ValueColumnChanged(int RowIndex, int ColumnIndex)
        {
            GridPanel e = GridDB1.PrimaryGrid;
            GridColumn gc = e.Columns[ColumnIndex];

            if (gc.EditControl.GetType() == typeof(SCBX.GridMultiComboBox))
            {
                GridRow gr = (GridRow)e.GridPanel.ActiveRow;
                GridMultiComboBox cl = (GridMultiComboBox)gc.EditControl;

                //if (cl.SelectedItem == null) { return; }
                if (cl.SelectedItem == null && e.Columns[ColumnIndex].Name == "clInventoryID") //e.GridCell.Value == null || 
                {
                    gr["clInventoryName"].Value = null;
                    gr["clQuantity"].Value = 0;
                    gr["clUnitID"].Value = null;
                    gr["clUnitPrice"].Value = 0;
                    gr["clOriginalAmount"].Value = 0;
                    gr["clConvertedAmount"].Value = 0;
                    gr["clImTaxConvertedAmount"].Value = 0;
                    gr["clExpenseConvertedAmount"].Value = 0;
                    Cal_Price();
                    return;
                }
                // if (e.GridCell.Value.ToString().Trim() == "") { return; }
                if (e.Columns[ColumnIndex].Name == "clInventoryID")
                {
                    gr["clInventoryName"].Value = cl.SelectedItem.ItemData[1];
                    gr["clQuantity"].Value = 1.0;
                    gr["clUnitID"].Value = cl.SelectedItem.ItemData[2];
                    gr["clUnitPrice"].Value = 0;//cl.SelectedItem.ItemData[3] != null ? cl.SelectedItem.ItemData[3] : "0"; //3-7 la gia
                    gr["clDebitAccountID"].Value = cl.SelectedItem.ItemData[3];
                    gr["clCreditAccountID"].Value = cl.SelectedItem.ItemData[4];
                    gr["clAna01ID"].Value = cl.SelectedItem.ItemData[5];
                    gr["clAna02ID"].Value = cl.SelectedItem.ItemData[6];
                    gr["clAna03ID"].Value = cl.SelectedItem.ItemData[7];
                    gr["clAna04ID"].Value = cl.SelectedItem.ItemData[8];
                    gr["clAna05ID"].Value = cl.SelectedItem.ItemData[9];
                    gr["clImTaxConvertedAmount"].Value = 0;
                    gr["clExpenseConvertedAmount"].Value = 0;
                }
            }
            Cal_Price();
        }

        private void GridDB2_ValueColumnChanged(int RowIndex, int ColumnIndex)
        {
            GridPanel e = GridDB2.PrimaryGrid;
            GridColumn gc = e.Columns[ColumnIndex];

            if (gc.EditControl.GetType() == typeof(SCBX.GridMultiComboBox))
            {
                GridRow gr = (GridRow)e.GridPanel.ActiveRow;
                GridMultiComboBox cl = (GridMultiComboBox)gc.EditControl;

                if (e.Columns[ColumnIndex].Name == "clCurrencyID")
                {
                    gr["clExchangeRate"].Value = cl.SelectedItem!=null?double.Parse(cl.SelectedItem.ItemData[2]):0.0;
                }
                else if (e.Columns[ColumnIndex].Name == "clObjectID")
                {
                    gr["clObjectName"].Value = cl.SelectedItem != null ? cl.SelectedItem.ItemData[1] : "";
                }
            }
            Cal_Price2();
        }

        private void GridDB3_ValueColumnChanged(int RowIndex, int ColumnIndex)
        {
            GridPanel e = GridDB3.PrimaryGrid;
            GridColumn gc = e.Columns[ColumnIndex];

            if (e.Columns[ColumnIndex].Name == "clOriginalAmount")
            {
                //Cal_Price3();
            }
            Cal_Price3();
        }

        private void GridDB1_EndEdit(object sender, DevComponents.DotNetBar.SuperGrid.GridEditEventArgs e)
        {
            GridDB1_ValueColumnChanged(e.GridCell.RowIndex, e.GridCell.ColumnIndex);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!Check_Form()) { return; }
            if (!Check_Table()) { return; }            

            if (_isNew)
            {
                if (DLL01.GetID("tb0191", "VoucherNo", txtVoucherNo.Text, "", FRM.ConnectString))
                {
                    if (DLL02.Confirm("Số chứng từ này đã có. Bạn có muốn tạo số chứng từ mới không?", "Xác nhận"))
                    {
                        DLL01.Get_VoucherNo(ref igb, FRM.ConnectString, TDBCboVoucherTypeID.Text, txtVoucherNo, "tb0191", FRM.Month, FRM.Year, FRM.DivisionID);
                    }
                    return;
                }
            }

            if (txtExpenseConvertedAmount.Value > 0)
            {
                if (!Check_Form2()) { tabControl1.SelectTab(1); return; }
                if (!Check_Table2()) { tabControl1.SelectTab(1); return; }
            }

            if (txtImTaxConvertedAmount.Value > 0)
            {
                if (!Check_Form3()) { tabControl1.SelectTab(2); return; }
                if (!Check_Table3()) { tabControl1.SelectTab(2); return; };
            }

            Save_Table();
        }

        private bool Check_Form()
        {
            if (TDBCboVoucherTypeID.Text == "")
            {
                DLL02.Alert("Bạn phải chọn loại chứng từ");
                TDBCboVoucherTypeID.Focus();
                return false;
            }
            else if (TDBCboCurrencyID.Text == "")
            {
                DLL02.Alert("Bạn phải chọn loại tiền");
                TDBCboCurrencyID.Focus();
                return false;
            }
            else if (TDBCboObjectID.Text == "")
            {
                DLL02.Alert("Bạn phải chọn đối tượng");
                TDBCboObjectID.Focus();
                return false;
            }
            else if (chkVAT.Checked)
            {
                if (TDBCboObjectIDVAT.Text == "")
                {
                    DLL02.Alert("Bạn phải chọn đối tượng thuế GTGT");
                    TDBCboObjectIDVAT.Focus();
                    return false;
                }
                else if (TDBCboDebitAccountID.Text == "")
                {
                    DLL02.Alert("Bạn phải chọn tài khoản Nợ");
                    TDBCboDebitAccountID.Focus();
                    return false;
                }
                else if (TDBCboCreditAccountID.Text == "")
                {
                    DLL02.Alert("Bạn phải chọn tài khoản Có");
                    TDBCboCreditAccountID.Focus();
                    return false;
                }
                else if (TDBCboVATGroupID.Text == "")
                {
                    DLL02.Alert("Bạn phải chọn nhóm thuế");
                    TDBCboVATGroupID.Focus();
                    return false;
                }
            }
            //Check ngày hạch toán
            //....

            return true;
        }

        private bool Check_Table()
        {
            GridDB1.Update();
            if (GridDB1.PrimaryGrid.Rows.Count < 2)
            {
                DLL02.Alert("Bạn phải nhập chi tiết hóa đơn");
                return false;
            }
            else if (GridDB1.PrimaryGrid.Rows.Count > 0)
            {
                int count_valid = 0;
                for (int i = 0; i < GridDB1.PrimaryGrid.Rows.Count; i++)
                {
                    if (GridDB1.PrimaryGrid.GetCell(i, 0).Value == null || GridDB1.PrimaryGrid.GetCell(i, 1).Value == null) { continue; }
                    if (GridDB1.PrimaryGrid.GetCell(i, 1).Value.ToString().Trim() == "") { continue; }
                    count_valid++;
                }
                if (count_valid == 0)
                {
                    GridDB1.PrimaryGrid.Rows.Clear();
                    DLL02.Alert("Bạn phải nhập chi tiết hóa đơn");
                    return false;
                }
            }
            return true;
        }

        private bool Check_Form2()
        {
            if (TDBCboVoucherTypeID2.Text == "")
            {
                DLL02.Alert("Bạn phải chọn loại chứng từ cho 'Chi phí mua hàng'");
                TDBCboVoucherTypeID2.Focus();
                return false;
            }
            else if (txtVoucherNo2.Text == "")
            {
                DLL02.Alert("Bạn phải chọn mã chứng từ");
                txtVoucherNo2.Focus();
                return false;
            }
            else if (TDBCboEmployeeID2.Text == "")
            {
                DLL02.Alert("Bạn phải chọn đối tượng");
                TDBCboEmployeeID2.Focus();
                return false;
            }

            //check số chứng từ không trùng
            if (_isNew)
            {
                if (DLL01.GetID("tb0191", "VoucherNo", txtVoucherNo2.Text, "", FRM.ConnectString))
                {
                    if (DLL02.Confirm("Số chứng từ này đã có. Bạn có muốn tạo số chứng từ mới không?", "Xác nhận"))
                    {
                        DLL01.Get_VoucherNo(ref igb2, FRM.ConnectString, TDBCboVoucherTypeID2.Text, txtVoucherNo2, "tb0191", FRM.Month, FRM.Year, FRM.DivisionID);
                    }
                    return false;
                }
            }

            return true;
        }

        private bool Check_Form3()
        {
            if (TDBCboVoucherTypeID3.Text == "")
            {
                DLL02.Alert("Bạn phải chọn loại chứng từ cho 'Thuế nhập khẩu'");
                TDBCboVoucherTypeID3.Focus();
                return false;
            }
            else if (txtVoucherNo3.Text == "")
            {
                DLL02.Alert("Bạn phải chọn mã chứng từ");
                txtVoucherNo3.Focus();
                return false;
            }
            else if (TDBCboObjectID3.Text == "")
            {
                DLL02.Alert("Bạn phải chọn đối tượng");
                TDBCboObjectID3.Focus();
                return false;
            }
            else if (TDBCboObjectID3.Text == "")
            {
                DLL02.Alert("Bạn phải chọn đối tượng");
                TDBCboObjectID3.Focus();
                return false;
            }
            else if (TDBCboCurrencyID3.Text == "")
            {
                DLL02.Alert("Bạn phải chọn loại tiền");
                TDBCboCurrencyID3.Focus();
                return false;
            }
            
            //check số chứng từ không trùng
            if (_isNew)
            {
                if (DLL01.GetID("tb0191", "VoucherNo", txtVoucherNo3.Text, "", FRM.ConnectString))
                {
                    if (DLL02.Confirm("Số chứng từ này đã có. Bạn có muốn tạo số chứng từ mới không?", "Xác nhận"))
                    {
                        DLL01.Get_VoucherNo(ref igb3, FRM.ConnectString, TDBCboVoucherTypeID3.Text, txtVoucherNo3, "tb0191", FRM.Month, FRM.Year, FRM.DivisionID);
                    }
                    return false;
                }
            }

            return true;
        }

        private bool Check_Table2()
        {
            GridDB2.Update();
            if (GridDB2.PrimaryGrid.Rows.Count < 2)
            {
                DLL02.Alert("Bạn phải nhập chi tiết 'Chi phi mua hàng'");
                return false;
            }
            else if (GridDB2.PrimaryGrid.Rows.Count > 0)
            {
                int count_valid = 0;
                for (int i = 0; i < GridDB2.PrimaryGrid.Rows.Count; i++)
                {
                    if (GridDB2.PrimaryGrid.GetCell(i, 0).Value == null || GridDB2.PrimaryGrid.GetCell(i, 1).Value == null || GridDB2.PrimaryGrid.GetCell(i, 2).Value == null) { continue; }
                    if (GridDB2.PrimaryGrid.GetCell(i, 1).Value.ToString().Trim() == "" || GridDB2.PrimaryGrid.GetCell(i, 2).Value.ToString().Trim() == "") { continue; }
                    count_valid++;
                }
                if (count_valid == 0)
                {
                    GridDB2.PrimaryGrid.Rows.Clear();
                    DLL02.Alert("Bạn phải nhập chi tiết 'Chi phi mua hàng'");
                    return false;
                }
            }

            //check bảng đã thay đổi nhưng chưa xác nhận thay đổi mới
            if(double.Parse(lblTotal2.Text)!=txtExpenseConvertedAmount.Value)
            {
                DLL02.Info("Bạn đã thay đổi chi tiết 'Chi phi mua hàng'\nVui lòng xác nhận thay đổi trước khi lưu.");
                return false;
            }
            return true;
        }

        private bool Check_Table3()
        {
            GridDB3.Update();
            if (GridDB3.PrimaryGrid.Rows.Count < 1)
            {
                DLL02.Alert("Bạn phải nhập chi tiết 'Thuế nhập khẩu'");
                return false;
            }
            else if (GridDB3.PrimaryGrid.Rows.Count > 0)
            {
                int count_valid = 0;
                for (int i = 0; i < GridDB3.PrimaryGrid.Rows.Count; i++)
                {
                    if (GridDB3.PrimaryGrid.GetCell(i, 0).Value == null || GridDB3.PrimaryGrid.GetCell(i, 1).Value == null) { continue; }
                    if (GridDB3.PrimaryGrid.GetCell(i, 1).Value.ToString().Trim() == "") { continue; }
                    count_valid++;
                }
                if (count_valid == 0)
                {
                    GridDB3.PrimaryGrid.Rows.Clear();
                    DLL02.Alert("Bạn phải nhập chi tiết 'Thuế nhập khẩu'");
                    return false;
                }
            }

            //check bảng đã thay đổi nhưng chưa xác nhận thay đổi mới
            if (double.Parse(lblTotal2.Text) != txtExpenseConvertedAmount.Value)
            {
                DLL02.Info("Bạn đã thay đổi chi tiết 'Thuế nhập khẩu'\nVui lòng xác nhận thay đổi trước khi lưu.");
                return false;
            }

            return true;
        }

        private void Delete_Record()
        {
            // xóa chi tiết phiếu bán hàng
            sql = string.Format("DELETE tb0191 Where DivisionID = '{0}' AND VoucherID = '{1}' AND BatchID = '{2}' AND TransactionTypeID = 'T03' ", FRM.DivisionID, _VoucherID, _BatchID);
            DATA.ExecuteNonQuery(sql, FRM.ConnectString);

            // xóa thuế của phiếu bán hàng
            sql = string.Format("DELETE tb0191 Where DivisionID = '{0}' AND VoucherID = '{1}' AND BatchID = '{2}' AND TransactionTypeID = 'T13' ", FRM.DivisionID, _VoucherID, _BatchID);
            DATA.ExecuteNonQuery(sql, FRM.ConnectString);
        }

        void DeleteTaxRecord()
        {
            sql = string.Format("Delete From tb0191 Where VoucherID='{0}' And TransactionTypeID='T33' And DivisionID = '{1}'  And TranMonth= '{2}' And TranYear = '{3}'", _VoucherID, FRM.DivisionID, FRM.Month, FRM.Year);
            DATA.ExecuteNonQuery(sql, FRM.ConnectString, true);
        }

        void DeleteCostRecord()
        {
            sql = string.Format("Delete From tb0191 Where VoucherID='{0}' And TransactionTypeID='T23' And DivisionID = '{1}'  And TranMonth= '{2}' And TranYear = '{3}'", _VoucherID, FRM.DivisionID, FRM.Month, FRM.Year);
            DATA.ExecuteNonQuery(sql, FRM.ConnectString, true);
        }

        private void Save_Table()
        {
            // Lấy [VoucherID, BatchID]

            string VoucherID = _VoucherID;
            string BatchID = _BatchID;
            if (_isNew)
            {
                VoucherID = DLL01.Get_VoucherID(FRM.ConnectString, "tb0191", "AV", FRM.Year, "");
                BatchID = DLL01.Get_BatchID(FRM.ConnectString, "tb0191", "AB", FRM.Year, "");
            }
            else
            {
                Delete_Record();
            }

            string sql = "";

            for (int i = 0; i < GridDB1.PrimaryGrid.Rows.Count; i++)
            {
                if (GridDB1.PrimaryGrid.GetCell(i, 0).Value == null || GridDB1.PrimaryGrid.GetCell(i, 1).Value == null) { continue; }
                if (GridDB1.PrimaryGrid.GetCell(i, 1).Value.ToString().Trim() == "") { continue; }

                string TransactionID = DLL01.Get_TransactionID(FRM.ConnectString, "tb0191", "AT", FRM.Year, "");
                GridDB1.PrimaryGrid.GetCell(i, 18).Value = TransactionID;

                sql = "INSERT tb0191 (VoucherID,BatchID,TransactionID,TableID,DivisionID,TranMonth,TranYear,TransactionTypeID,";
                sql += "CurrencyID,ObjectID,CreditObjectID,VATNo, VATObjectID, VATObjectName, VATObjectAddress, DebitAccountID, CreditAccountID, ExchangeRate,";
                sql += "UnitPrice, OriginalAmount, ConvertedAmount,IsStock, VoucherDate, InvoiceDate,";
                sql += "VoucherTypeID, VATTypeID, VATGroupID, VoucherNo, Serial, InvoiceNo, Orders,";
                sql += "EmployeeID, SenderReceiver, SRDivisionName, SRAddress, VDescription, BDescription, TDescription,";
                sql += "Quantity, InventoryID, UnitID, Status, IsAudit, IsCost,";
                sql += "Ana01ID, Ana02ID, Ana03ID, Ana04ID, Ana05ID,";
                sql += "InventoryName1,TypeVoice, DueDate, PaymentTermID, ";
                sql += "ExpenseOriginalAmount, ExpenseConvertedAmount, ImTaxOriginalAmount, ImTaxConvertedAmount, ";
                sql += "CreateDate, CreateUserID, LastModifyDate, LastModifyUserID, Barcode)";
                sql += "VALUES(";
                sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',N'{5}',N'{6}',N'{7}',", VoucherID, BatchID, TransactionID, "tb0191", FRM.DivisionID, FRM.Month, FRM.Year, "T03");
                sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',N'{5}',N'{6}',N'{7}',N'{8}',N'{9}',", TDBCboCurrencyID.Text, TDBCboObjectID.Text, DBNull.Value, txtVATNo.Text, TDBCboVATObjectID.Text, txtVATObjectName.Text, txtVATObjectAddress.Text, GridDB1.PrimaryGrid.GetCell(i, 8).Value, GridDB1.PrimaryGrid.GetCell(i, 9).Value, txtExchangeRate.Text);
                sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',N'{5}',", GridDB1.PrimaryGrid.GetCell(i, 5).Value, GridDB1.PrimaryGrid.GetCell(i, 6).Value, GridDB1.PrimaryGrid.GetCell(i, 7).Value, chkIsStock.Checked ? "1" : "0", dtpVoucherDate.Value.Date, dtpInvoiceDate.Value.Date);
                sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',N'{5}',N'{6}',", TDBCboVoucherTypeID.Text, TDBCboVATTypeID.Text, TDBCboVATGroupID.Text, txtVoucherNo.Text, txtSerial.Text, txtInvoiceNo.Text, GridDB1.PrimaryGrid.GetCell(i, 0).Value);
                sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',N'{5}',N'{6}',", DBNull.Value, txtVATObjectName.Text, txtVATObjectName.Text, txtVATObjectAddress.Text, txtVDescription.Text, txtBDescription.Text, GridDB1.PrimaryGrid.GetCell(i, 10).Value);
                sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',N'{5}',", GridDB1.PrimaryGrid.GetCell(i, 3).Value, GridDB1.PrimaryGrid.GetCell(i, 1).Value, GridDB1.PrimaryGrid.GetCell(i, 4).Value, 0, 0, 0);
                sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',", GridDB1.PrimaryGrid.GetCell(i, 13).Value, GridDB1.PrimaryGrid.GetCell(i, 14).Value, GridDB1.PrimaryGrid.GetCell(i, 15).Value, GridDB1.PrimaryGrid.GetCell(i, 16).Value, GridDB1.PrimaryGrid.GetCell(i, 17).Value);
                sql += string.Format("N'{0}',N'{1}', {2}, '{3}',", GridDB1.PrimaryGrid.GetCell(i, 2).Value, txtTypeVoice.Text, dtpDueDate.Checked ? "'" + dtpDueDate.Value.ToShortDateString() + "'" : "NULL", TDBCboPaymentTermID.Text);
                sql += string.Format("N'{0}',N'{0}', '{1}', '{1}',", GridDB1.PrimaryGrid.GetCell(i, 11).Value, GridDB1.PrimaryGrid.GetCell(i, 12).Value);
                sql += string.Format("GETDATE(),N'{0}',GETDATE(),N'{0}',N'{1}')", FRM.UserName, DBNull.Value);

                DATA.ExecuteNonQuery(sql, FRM.ConnectString, true);

                // T03: Phiếu mua hàng
                // T23: Giá bán hàng
                // T33: Thuế nhập khẩu

            }      

            if (chkVAT.Checked)
            {

                string TransactionID = DLL01.Get_TransactionID(FRM.ConnectString, "tb0191", "AT", FRM.Year, "");

                sql = "Insert tb0191 (PaymentTermID,VoucherID,BatchID,TransactionID,TableID, DivisionID,TranMonth,TranYear,TransactionTypeID,";
                sql += " CurrencyID, ObjectID, VATObjectID,";
                sql += " VATObjectName, VATNo,VATObjectAddress, SRDivisionName, SRAddress, SenderReceiver, ";
                sql += " CreditAccountID, DebitAccountID, ExchangeRate, OriginalAmount, ConvertedAmount, VoucherDate, DueDate,";
                sql += " OriginalAmountCN,ExchangeRateCN,CurrencyIDCN, ";
                sql += " InvoiceDate, VoucherTypeID, VATTypeID, VATGroupID, VoucherNo, Serial, TypeVoice,";
                sql += " InvoiceNo, Orders, EmployeeID, RefNo01,RefNo02, VDescription, BDescription, TDescription, ";
                sql += " Quantity, UnitPrice, InventoryID, UnitID, Status, IsAudit, OrderID, ";
                sql += " ImTaxOriginalAmount, ImTaxConvertedAmount, ExpenseOriginalAmount, ExpenseConvertedAmount, ";
                sql += " Ana01ID, Ana02ID, Ana03ID, Ana04ID,Ana05ID,";
                sql += " CreateDate, CreateUserID, LastModifyDate, LastModifyUserID, Barcode) Values(";

                sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',N'{5}',N'{6}',N'{7}',N'{8}',", TDBCboPaymentTermID.Text, VoucherID, BatchID, TransactionID, "tb0191", FRM.DivisionID, FRM.Month, FRM.Year, "T13"); //T03: Phiếu mua hàng
                sql += string.Format("N'{0}',N'{1}',N'{2}',", TDBCboCurrencyID.Text, TDBCboObjectIDVAT.Text, TDBCboVATObjectID.Text);
                sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',N'{5}',", txtVATObjectName.Text, txtVATNo.Text, txtVATObjectAddress.Text, txtVATObjectName.Text, txtVATObjectAddress.Text, txtVATObjectName.Text);
                sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',N'{5}',{6},", TDBCboCreditAccountID.Text, TDBCboDebitAccountID.Text, txtExchangeRate.Value, txtVATAmount.Value, txtVATConvertedAmount.Value, dtpVoucherDate.Value, dtpDueDate.Checked ? "'" + dtpDueDate.Value.ToShortDateString() + "'" : "NULL");
                sql += string.Format("N'{0}',N'{1}',N'{2}',", txtVATAmount.Value, txtExchangeRate.Value, TDBCboCurrencyID.Text);
                sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',N'{5}', '{6}',", dtpInvoiceDate.Value, TDBCboVoucherTypeID.Text, TDBCboVATTypeID.Text, TDBCboVATGroupID.Text, txtVoucherNo.Text, txtSerial.Text, txtTypeVoice.Text);
                sql += string.Format("N'{0}',N'0',NULL,NULL,NULL,N'{1}',N'{2}',N'{3}',", txtInvoiceNo.Text, txtVDescription.Text, txtBDescription.Text, txtTDescription.Text);
                sql += "NULL,NULL,NULL,NULL,0,0, NULL,";
                sql += "NULL,NULL,NULL,NULL,";
                sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',", GridDB1.PrimaryGrid.GetCell(0, 13).Value.ToString(), GridDB1.PrimaryGrid.GetCell(0, 14).Value.ToString(), GridDB1.PrimaryGrid.GetCell(0, 15).Value.ToString(), GridDB1.PrimaryGrid.GetCell(0, 16).Value.ToString(), GridDB1.PrimaryGrid.GetCell(0, 17).Value.ToString());
                sql += string.Format("GETDATE(),N'{0}',GETDATE(),N'{0}',N'{1}')", FRM.UserName, DBNull.Value);

                DATA.ExecuteNonQuery(sql, FRM.ConnectString, false);

            }

            DeleteCostRecord();

            if (txtExpenseConvertedAmount.Value > 0)
            {
                // lưu dữ liệu cho tab [2] Chi phí mua hàng (frm0219)
                string BatchID2 = DLL01.Get_BatchID(FRM.ConnectString, "tb0191", "AB", FRM.Year, "");          

                for (int i = 0; i < GridDB2.PrimaryGrid.Rows.Count; i++)
                {
                    if (GridDB2.GetCellVal(i, 0) == null || GridDB2.GetCellVal(i, 1) == null) { continue; }

                    string TransactionID = DLL01.Get_TransactionID(FRM.ConnectString, "tb0191", "AT", FRM.Year, "");
                    sql = "Insert tb0191 (VoucherID,BatchID,TransactionID,TableID,DivisionID,TranMonth,TranYear,";
                    sql += " TransactionTypeID, CurrencyID, ObjectID, CreditObjectID, VATObjectID,VATObjectName,VATNO,";
                    sql += " DebitAccountID, CreditAccountID, ExchangeRate, OriginalAmount, ConvertedAmount, VoucherDate, ";
                    sql += " OriginalAmountCN,ExchangeRateCN,CurrencyIDCN, ";
                    sql += " InvoiceDate, VoucherTypeID, VATTypeID, VATGroupID, VoucherNo, Serial,";
                    sql += " InvoiceNo, Orders, EmployeeID, RefNo01,RefNo02, VDescription, BDescription, TDescription, ";
                    sql += " Quantity, InventoryID, UnitID, Status, IsAudit, ";
                    sql += " SenderReceiver, SRAddress, ";
                    sql += " Ana01ID, Ana02ID, Ana03ID,Ana04ID,Ana05ID, OrderID, PeriodID, ProductID, ";
                    sql += " CreateDate, CreateUserID, LastModifyDate, LastModifyUserID ) Values(";

                    sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',N'{5}',N'{6}',", VoucherID, BatchID2, TransactionID, "tb0191", FRM.DivisionID, FRM.Month, FRM.Year);
                    sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',N'{5}',N'{6}',", "T23", GridDB2.GetCellVal(i, 4), GridDB2.GetCellVal(i, 10), "", "", "", "");
                    sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',N'{5}',", GridDB2.GetCellVal(i, 8), GridDB2.GetCellVal(i, 9), GridDB2.GetCellVal(i, 5), GridDB2.GetCellVal(i, 6), GridDB2.GetCellVal(i, 7), dtpVoucherDate2.Value);
                    sql += string.Format("N'{0}',N'{1}',N'{2}',", GridDB2.GetCellVal(i, 6), GridDB2.GetCellVal(i, 5), GridDB2.GetCellVal(i, 4));
                    sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',N'{5}',", GridDB2.GetCellVal(i, 3), TDBCboVoucherTypeID2.Text, GridDB2.GetCellVal(i, 13), GridDB2.GetCellVal(i, 14), txtVoucherNo2.Text, GridDB2.GetCellVal(i, 1));
                    sql += string.Format("N'{0}',N'{1}',N'{2}',  {3}, {4},   N'{5}',N'{6}',N'{7}',", GridDB2.GetCellVal(i, 2), GridDB2.GetCellVal(i, 0), TDBCboEmployeeID2.Text, "NULL", "NULL", txtDescription2.Text, GridDB2.GetCellVal(i, 15), GridDB2.GetCellVal(i, 16));
                    sql += string.Format("{0}, {1}, {2},N'{3}',N'{4}',", "NULL", "NULL", "NULL", 0, 0);
                    sql += string.Format("{0},{1}, ", "NULL", "NULL");
                    sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}', {5} , {6} , {7} ,", GridDB2.GetCellVal(i, 17), GridDB2.GetCellVal(i, 18), GridDB2.GetCellVal(i, 19), GridDB2.GetCellVal(i, 20), GridDB2.GetCellVal(i, 21), "NULL", "NULL", "NULL");
                    sql += string.Format("GETDATE(),N'{0}',GETDATE(),N'{0}')", FRM.UserName);

                    DATA.ExecuteNonQuery(sql, FRM.ConnectString, false);
                }

                if (_isNew || _isDuplicate) { igb2.SaveNewKey(); } 
            }

            DeleteTaxRecord();

            if (txtImTaxConvertedAmount.Value > 0)
            {
                // lưu dữ liệu cho tab [3] Thuế nhập khẩu (frm0221)
                string BatchID3 = DLL01.Get_BatchID(FRM.ConnectString, "tb0191", "AB", FRM.Year, "");
                
                for (int i = 0; i < GridDB3.PrimaryGrid.Rows.Count; i++)
                {
                    if (GridDB3.GetCellVal(i, 0) == null || GridDB3.GetCellVal(i, 1) == null) { continue; }

                    string TransactionID = DLL01.Get_TransactionID(FRM.ConnectString, "tb0191", "AT", FRM.Year, "");
                    sql = "Insert tb0191 (VoucherID,BatchID,TransactionID,TableID,DivisionID,TranMonth,";
                    sql += " TranYear,TransactionTypeID, CurrencyID, CurrencyIDCN, ObjectID,";
                    sql += " CreditAccountID, DebitAccountID, ExchangeRate,ExchangeRateCN,OriginalAmount, OriginalAmountCN, ";
                    sql += " ConvertedAmount, VoucherDate, InvoiceDate, VoucherTypeID, VATTypeID, VoucherNo, Serial,";
                    sql += " InvoiceNo, VDescription, BDescription, TDescription, TypeVoice, ";
                    sql += " Ana01ID, Ana02ID, Ana03ID, Ana04ID,Ana05ID,";
                    sql += " CreateDate, CreateUserID, LastModifyDate, LastModifyUserID ) Values(";

                    sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',N'{5}',", VoucherID, BatchID3, TransactionID, "tb0191", FRM.DivisionID, FRM.Month);
                    sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',", FRM.Year, "T33", TDBCboCurrencyID3.Text, TDBCboCurrencyID3.Text, TDBCboObjectID3.Text);
                    sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',N'{5}',", GridDB3.GetCellVal(i, 1), GridDB3.GetCellVal(i, 0), txtExchangeRate3.Value, txtExchangeRate3.Value, GridDB3.GetCellVal(i, 2), GridDB3.GetCellVal(i, 2));
                    sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',N'{5}',N'{6}',", GridDB3.GetCellVal(i, 3), dtpVoucherDate3.Value, dtpPickerInvoiceDate3.Value, TDBCboVoucherTypeID3.Text, TDBCboVATTypeID3.Text, txtVoucherNo3.Text, txtSerial.Text);
                    sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',", txtInvoiceNo3.Text, txtDescription3.Text, txtDescription3.Text, GridDB3.GetCellVal(i, 9), txtTypeVoice3.Text);
                    sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',", GridDB3.GetCellVal(i, 4), GridDB3.GetCellVal(i, 5), GridDB3.GetCellVal(i, 6), GridDB3.GetCellVal(i, 7), GridDB3.GetCellVal(i, 8));
                    sql += string.Format("GETDATE(),N'{0}',GETDATE(),N'{0}')", FRM.UserName);

                    DATA.ExecuteNonQuery(sql, FRM.ConnectString, true);
                }

                if (_isNew || _isDuplicate) { igb3.SaveNewKey(); }                    
            }


            if (_isNew || _isDuplicate)
            {
                igb.SaveNewKey();
                (Application.OpenForms["frm0244"] as frm0244).loadDATA_Grid();
            }
            DLL02.Info("Lưu dữ liệu thành công");
            btnSave.Enabled = false;
            btnImputWareHouse.Enabled = true;
            _VoucherID = VoucherID;
            _BatchID = BatchID;
        }        

        private void btnChiphimuahang_Click(object sender, EventArgs e)
        {
            tabControl1.SelectTab(1);
        }

        private void btnThuenhapkhau_Click(object sender, EventArgs e)
        {
            tabControl1.SelectTab(2);
        }

        private void TDBCboEmployeeID2_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (TDBCboEmployeeID2.SelectedItem != null) { txtEmployeeName2.Text = TDBCboEmployeeID2.SelectedItem.ItemData[1]; }
            else { txtEmployeeName2.Text = ""; }
        }

        private void TDBCboVoucherTypeID2_SelectedIndexChanged(object sender, EventArgs e)
        {
            DLL01.Get_VoucherNo(ref igb2, FRM.ConnectString, TDBCboVoucherTypeID2.Text, txtVoucherNo2, "tb0191", FRM.Month, FRM.Year, FRM.DivisionID);
        }

        private void GridDB2_EndEdit(object sender, GridEditEventArgs e)
        {
            GridDB2_ValueColumnChanged(e.GridCell.RowIndex, e.GridCell.ColumnIndex);
        }               

        private void GridDB3_EndEdit(object sender, GridEditEventArgs e)
        {
            GridDB3_ValueColumnChanged(e.GridCell.RowIndex, e.GridCell.ColumnIndex);
        }

        private void TDBCboVoucherTypeID3_SelectedIndexChanged(object sender, EventArgs e)
        {
            DLL01.Get_VoucherNo(ref igb3, FRM.ConnectString, TDBCboVoucherTypeID3.Text, txtVoucherNo3, "tb0191", FRM.Month, FRM.Year, FRM.DivisionID);
        
        }

        private void TDBCboCurrencyID3_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtExchangeRate3.Text = TDBCboCurrencyID3.SelectedItem != null ? TDBCboCurrencyID3.SelectedItem.ItemData[2] : "0";
            if (GridDB2.PrimaryGrid.Rows.Count > 0) { Cal_Price3(); }
        }

        private void TDBCboObjectID3_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (TDBCboObjectID3.SelectedItem != null) { txtObjectName3.Text = TDBCboObjectID3.SelectedItem.ItemData[1]; }
            else { txtObjectName3.Text = ""; }
        }

        private void btnOK2_Click(object sender, EventArgs e)
        {
            txtExpenseConvertedAmount.Value = double.Parse(lblTotal2.Text);
            tabControl1.SelectTab(0);
            if (double.Parse(lblTotal2.Text) > 0) {SplitImTaxANDExpense();}
        }

        private void btnDelete2_Click(object sender, EventArgs e)
        {
            if (!DLL02.Confirm("Bạn có chắc muốn xóa bỏ 'Chi phí mua hàng'")) { return; }
            GridDB2.PrimaryGrid.Rows.Clear();
            txtExpenseConvertedAmount.Value = 0;
            lblTotal2.Text = string.Format("{0:#,#.00}", 0);
        }

        private void btnOK3_Click(object sender, EventArgs e)
        {
            if (double.Parse(lblTotal3.Text) == 0) { return; }
            if (double.Parse(lblTotal3.Text)!=txtImTaxConvertedAmount.Value)
            {
                if(DLL02.Confirm("Thông tin 'Thuế nhập khẩu' giữa tab 'Thuế nhập khẩu' và chi tiết 'Chi phí mua hàng' không trùng khớp\nBạn có muốn cập nhật lại?"))
                {
                    Tranfer_Grid1_Grid3();
                    return;
                }
            }
            //txtImTaxConvertedAmount.Value = double.Parse(lblTotal3.Text);
            tabControl1.SelectTab(0);
            //SplitImTaxANDExpense();
        }

        private void btnDelete3_Click(object sender, EventArgs e)
        {
            if (!DLL02.Confirm("Bạn có chắc muốn xóa bỏ 'Thuế nhập khẩu'")) { return; }
            GridDB3.PrimaryGrid.Rows.Clear();
            txtImTaxConvertedAmount.Value = 0;
            lblTotal3.Text = string.Format("{0:#,#.00}", 0);
            for (int i = 0; i < GridDB1.PrimaryGrid.Rows.Count; i++)
                GridDB1.PrimaryGrid.GetCell(i, 12).Value = 0;
        }

        private void btnQuantity_Click(object sender, EventArgs e)
        {
            if (_isSlitA) { _isSlitA = false; btnSplitA.Text = "A"; } else { _isSlitA = true; btnSplitA.Text = "Q"; }
            SplitImTaxANDExpense();            
        }

        void SplitImTaxANDExpense()
        {
            if (_TotalQuantity > 0 && _isSlitA)
            {
                for (int i = 0; i < GridDB1.PrimaryGrid.Rows.Count; i++)
                    if (GridDB1.GetCellVal(i, 3) != null)
                    {
                        GridDB1.PrimaryGrid.GetCell(i, 11).Value = txtExpenseConvertedAmount.Value * double.Parse(GridDB1.GetCellVal(i, 3)) / _TotalQuantity;
                        //GridDB1.PrimaryGrid.GetCell(i, 12).Value = txtImTaxConvertedAmount.Value * double.Parse(GridDB1.GetCellVal(i, 3)) / _TotalQuantity;
                    }
            }

            if (_TotalPrice > 0 && !_isSlitA)
            {
                for (int i = 0; i < GridDB1.PrimaryGrid.Rows.Count; i++)
                    if (GridDB1.GetCellVal(i, 7) != null)
                    {
                        GridDB1.PrimaryGrid.GetCell(i, 11).Value = txtExpenseConvertedAmount.Value * double.Parse(GridDB1.GetCellVal(i, 7)) / _TotalPrice;
                        //GridDB1.PrimaryGrid.GetCell(i, 12).Value = txtImTaxConvertedAmount.Value * double.Parse(GridDB1.GetCellVal(i, 7)) / _TotalPrice;
                    }
            }
        }

        private void btnHelp_Click(object sender, EventArgs e)
        {
            //MessageBox.Show(GridDB2.PrimaryGrid.Rows.Count.ToString());
        }

        private void btnVoucherTypeIDSetting_Click(object sender, EventArgs e)
        {
            if (TDBCboVoucherTypeID.Text == "") { return; }
            Form frm = new frm0041(TDBCboVoucherTypeID.Text, TDBCboVoucherTypeID);
            frm.ShowDialog();
        }

        private void btnVoucherTypeIDSetting2_Click(object sender, EventArgs e)
        {
            if (TDBCboVoucherTypeID2.Text == "") { return; }
            Form frm = new frm0041(TDBCboVoucherTypeID2.Text, TDBCboVoucherTypeID2);
            frm.ShowDialog();
        }

        private void btnVoucherTypeIDSetting3_Click(object sender, EventArgs e)
        {
            if (TDBCboVoucherTypeID3.Text == "") { return; }
            Form frm = new frm0041(TDBCboVoucherTypeID3.Text, TDBCboVoucherTypeID3);
            frm.ShowDialog();
        }

        private void btnImputWareHouse_Click(object sender, EventArgs e)
        {
            Form frm = new frm0281(GridDB1, _VoucherID, _BatchID, txtVoucherNo.Text, TDBCboObjectID.Text, dtpVoucherDate.Value, txtVDescription.Text, txtObjectName.Text, txtVoucherNo.Text, "/");
            frm.ShowDialog();
        }

    }
}
